package com.ruoyi.translat.service.impl;

import com.ruoyi.common.translate.LanguageCodes;
import com.ruoyi.translat.domain.TencentTranslationDO;
import com.ruoyi.translat.domain.TencentTranslationIO;
import com.ruoyi.translat.domain.TranslatSecret;
import com.ruoyi.translat.mapper.TranslatSecretMapper;
import com.ruoyi.translat.service.TencentTranslationService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.tmt.v20180321.TmtClient;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateRequest;
import com.tencentcloudapi.tmt.v20180321.models.TextTranslateResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @Title:
 * @author: WYJ
 * @date: 2025/10/11
 */
@Slf4j
@Service
public class TencentTranslationServiceImpl implements TencentTranslationService {

    private static final Integer STR_LENGTH = 98;

    @Resource
    TranslatSecretMapper translatSecretMapper;

    private static final String ENDPOINT = "tmt.tencentcloudapi.com";
    private static final String REGION = "ap-shanghai";

    @Override
    public List<TencentTranslationDO> TencentTranslationData(List<TencentTranslationIO> list) {
        //获取翻译器：
        TmtClient translator = getTencentTranslator();
        List<TencentTranslationDO> reList = new ArrayList<>(16);
        if (translator == null) {
            return reList;
        }
        for (TencentTranslationIO im : list) {
            TencentTranslationDO io = new TencentTranslationDO();
            io.setChanne(im.getChanne());
            io.setTitle(im.getTitle());
            io.setEnglish(im.getEnglish());
            //自动检测翻译为英文
            String en = autoTranslate(io.getEnglish(), LanguageCodes.ENGLISH, translator);
            log.info("自动翻译{}", en);
            io.setEnglish(en);
            //翻译为中文
            String ch = getTranslateStr(io.getEnglish(), LanguageCodes.CHINESE, "中文", translator);
            //io.setChinese(ch);
            String ja = getTranslateStr(io.getEnglish(), LanguageCodes.JAPANESE, "日语", translator);
            io.setJapanese(ja);

            String ko = getTranslateStr(io.getEnglish(), LanguageCodes.KOREAN, "韩语", translator);
            io.setKorean(ko);

            String fr = getTranslateStr(io.getEnglish(), LanguageCodes.FRENCH, "法语", translator);
            io.setFrench(fr);
            String sp = getTranslateStr(io.getEnglish(), LanguageCodes.SPANISH, "西班牙", translator);
            io.setSpanish(sp);
            String ge = getTranslateStr(io.getEnglish(), LanguageCodes.GERMAN, "德语", translator);
            io.setGerman(ge);
           /* String ru = translator.translate(io.getTitle(), LanguageCodes.CHINESE, LanguageCodes.RUSSIAN);
            io.setRussian(ru);
            System.out.println("中译俄: " + ru);*/
            String ar = getTranslateStr(io.getEnglish(), LanguageCodes.ARAB, "阿拉伯", translator);
            io.setArab(ar);
            String po = getTranslateStr(io.getEnglish(), LanguageCodes.PORTUGUESE, "葡萄牙", translator);
            io.setPortuguese(po);
            String it = getTranslateStr(io.getEnglish(), LanguageCodes.ITALIAN, "意大利", translator);
            io.setItalian(it);
            String th = getTranslateStr(io.getEnglish(), LanguageCodes.THAILAND, "泰国语", translator);
            io.setThailand(th);

            //String km = getTranslateStr(io.getTitle(), LanguageCodes.CAMBODIA, "柬埔寨语",rateLimitedTranslator);
            //io.setCambodia(km);

            //String tl = getTranslateStr(io.getTitle(), LanguageCodes.PHILIPPINES, "律宾语",rateLimitedTranslator);
            //io.setPhilippines(tl);
            String ms = getTranslateStr(io.getEnglish(), LanguageCodes.MALAY, "马来语", translator);
            io.setMalay(ms);
            //String ta = getTranslateStr(io.getTitle(), LanguageCodes.THAMEL, "泰米尔语",rateLimitedTranslator);
            //io.setThamel(ta);
            String vi = getTranslateStr(io.getEnglish(), LanguageCodes.VIETNAM, "越南语", translator);

            io.setVietnam(vi);
            //String mya = getTranslateStr(io.getTitle(), LanguageCodes.MYANMAR, "缅甸语",rateLimitedTranslator);
            //io.setMyanmar(mya);
            String hi = getTranslateStr(io.getEnglish(), LanguageCodes.HINDI, "印地语", translator);
            io.setHindi(hi);

            String id = getTranslateStr(io.getEnglish(), LanguageCodes.INDONESIA, "印度尼西亚语", translator);
            io.setIndonesia(id);
            if (StringUtils.isNotBlank(en) && en.length() > STR_LENGTH) {
                // 中译英
                io.setEnglish(en.substring(0, STR_LENGTH));
            }

            reList.add(io);
        }

        return reList;
    }

    @Override
    public Map<String, String> tencentTranslationStr(String title) {
        Map<String, String> map = new LinkedHashMap<>(16);
        TmtClient translator = getTencentTranslator();
        if (translator == null) {
            return null;
        }
        map.put("原文", title);
        //自动检测翻译为英文
        String en = autoTranslate(title, LanguageCodes.ENGLISH, translator);
        log.info("自动翻译{}", en);
        //翻译为中文
        String ch = getTranslateStr(en, LanguageCodes.CHINESE, "中文", translator);
        map.put("中文", ch);
        map.put("英语", en);
        String ja = getTranslateStr(en, LanguageCodes.JAPANESE, "日语", translator);
        map.put("日语", ja);
        String ko = getTranslateStr(en, LanguageCodes.KOREAN, "韩语", translator);
        map.put("韩语", ko);
        String fr = getTranslateStr(en, LanguageCodes.FRENCH, "法语", translator);
        map.put("法语", fr);
        String sp = getTranslateStr(en, LanguageCodes.SPANISH, "西班牙", translator);
        map.put("西班牙", sp);
        String ge = getTranslateStr(en, LanguageCodes.GERMAN, "德语", translator);
        map.put("德语", ge);
        String ar = getTranslateStr(en, LanguageCodes.ARAB, "阿拉伯", translator);
        map.put("阿拉伯", ar);
        String po = getTranslateStr(en, LanguageCodes.PORTUGUESE, "葡萄牙", translator);
        map.put("葡萄牙", po);
        String it = getTranslateStr(en, LanguageCodes.ITALIAN, "意大利", translator);
        map.put("意大利", it);
        String th = getTranslateStr(en, LanguageCodes.THAILAND, "泰国语", translator);
        map.put("泰国语", th);
        String ms = getTranslateStr(en, LanguageCodes.MALAY, "马来语", translator);
        map.put("马来语", ms);
        String vi = getTranslateStr(en, LanguageCodes.VIETNAM, "越南语", translator);
        map.put("越南语", vi);
        String hi = getTranslateYindi(en, LanguageCodes.HINDI, "印地语", translator);
        map.put("印地语", hi);
        String id = getTranslateStr(en, LanguageCodes.INDONESIA, "印度尼西亚语", translator);
        map.put("印度尼西亚语", id);
        if (StringUtils.isNotBlank(en) && en.length() > STR_LENGTH) {
            map.put("英语", en.substring(0, STR_LENGTH));
        }
        return map;
    }

    private TmtClient getTencentTranslator() {
        //从数据库获取密钥
        TranslatSecret re = translatSecretMapper.selectTranslatSecretByType("Tencent");
        if (re == null || StringUtils.isBlank(re.getSecretId()) || StringUtils.isBlank(re.getSecretKey())) {
            return null;
        }
        log.info("TranslatSecret ", re);
        // 初始化认证对象
        Credential cred = new Credential(re.getSecretId(), re.getSecretKey());

        // 客户端配置
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(ENDPOINT);

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        return new TmtClient(cred, REGION, clientProfile);
    }

    /**
     * 文本翻译
     *
     * @param sourceText 源文本
     * @param sourceLang 源语言，如：zh
     * @param targetLang 目标语言，如：en
     * @return 翻译结果
     */
    public String translate(String sourceText, String sourceLang, String targetLang, TmtClient client) {
        try {
            TextTranslateRequest req = new TextTranslateRequest();
            req.setSourceText(sourceText);
            req.setSource(sourceLang);
            req.setTarget(targetLang);
            req.setProjectId(0L); // 项目ID，0表示默认项目

            TextTranslateResponse resp = client.TextTranslate(req);
            return resp.getTargetText();

        } catch (TencentCloudSDKException e) {
            System.err.println("翻译失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 自动检测语言并翻译
     *
     * @param sourceText 源文本
     * @param targetLang 目标语言
     * @return 翻译结果
     */
    public String autoTranslate(String sourceText, String targetLang, TmtClient client) {
        return translate(sourceText, "auto", targetLang, client);
    }

    String getTranslateStr(String title, String code, String desc, TmtClient client) {
        String re = "";
        try {
            Thread.sleep(100);
            re = translate(title, LanguageCodes.ENGLISH, code, client);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("中译 " + desc + ": " + re);
        log.info("中译 " + desc + "长度: " + re.length());
        if (StringUtils.isNotBlank(re) && re.length() > STR_LENGTH) {
            re = re.substring(0, STR_LENGTH);
            log.info("截取后" + re);
        }
        return re;
    }

    String getTranslateStrTwo(String title, String code, String desc, String sour, TmtClient client) {
        String re = "";
        try {
            Thread.sleep(100);
            re = translate(title, sour, code, client);

        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("中译 " + desc + ": " + re);
        log.info("中译 " + desc + "长度: " + re.length());
        System.out.println("中译 " + desc + ": " + re);
        if (StringUtils.isNotBlank(re) && re.length() > STR_LENGTH) {
            re = re.substring(0, STR_LENGTH);
            log.info("截取后" + re);
        }
        return re;
    }

    String getTranslateYindi(String title, String code, String desc, TmtClient client) {
        String re = "";
        try {
            //Thread.sleep(30);
            String en = translate(title, LanguageCodes.CHINESE, LanguageCodes.ENGLISH, client);
            re = translate(en, LanguageCodes.ENGLISH, code, client);
        } catch (Exception e) {
            e.printStackTrace();
        }
        log.info("中译 " + desc + ": " + re);
        log.info("中译 " + desc + "长度: " + re.length());
        System.out.println("中译 " + desc + ": " + re);
        if (StringUtils.isNotBlank(re) && re.length() > STR_LENGTH) {
            re = re.substring(0, STR_LENGTH);
            log.info("截取后" + re);
        }
        return re;
    }
}
